package com.mall.ui;

import static com.examination.mlib.constants.AllStringConstants.FAQ_QUA;
import static com.examination.mlib.constants.AllStringConstants.getQuality;
import static com.examination.mlib.utils.LoginThenRouterUtils.RouterBean.TYPE_QUALIFY;
import static com.mall.bean.MallHomeContentBean.YCategoryList;
import static com.mall.bean.MallHomeContentBean.YHotSale;
import static com.mall.bean.MallHomeContentBean.YImage;
import static com.mall.bean.MallHomeContentBean.YSearch;
import static com.mall.bean.MallHomeContentBean.YSpecial;
import static com.mall.bean.MallHomeContentBean.YSwiper;
import static com.mall.bean.MallHomeContentBean.YWaterfallFlow;
import static com.mall.observer.MallObserver.TYPE_DRUGS_LOAD_ONE_PAGE;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import androidx.core.widget.NestedScrollView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.bumptech.glide.Glide;
import com.examination.mlib.baseold.ModuleBaseFragment;
import com.examination.mlib.bean.DefaultEntity;
import com.examination.mlib.bean.FaqEntity;
import com.examination.mlib.bean.SecretWordBean;
import com.examination.mlib.constants.ARouterConstants;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.constants.UserInfoConstants;
import com.examination.mlib.utils.LocationUtils;
import com.examination.mlib.utils.LoginThenRouterUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.mall.MallUtils;
import com.mall.R;
import com.mall.bean.MallHomeBean;
import com.mall.bean.MallHomeContentBean;
import com.mall.bean.YCategoryListBean;
import com.mall.bean.YHotSaleBean;
import com.mall.bean.YImageBean;
import com.mall.bean.YSpecialBean;
import com.mall.bean.YSwiperBean;
import com.mall.bean.YWaterfallFlowBean;
import com.mall.observer.MallObserver;
import com.mall.widget.MallCardView;
import com.mall.widget.MallClassifyView;
import com.mall.widget.MallDrugRecyclerView;
import com.mall.widget.MallHotView;
import com.mall.widget.MallNestedScrollView;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.ListUtil;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.ScreenUtils;
import com.yilijk.base.utils.SharedPreferencesUtils;
import com.yilijk.base.utils.ToastUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.loader.ImageLoader;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

@Route(path = ARouterConstants.MALL_FRAGMENT)
public class MallFragment extends ModuleBaseFragment implements Observer {
    private final int changeScrollH = 120;
    private MallNestedScrollView nestedScrollView;
    private TextView homeTv, homeFixedTv;
    private int homeTvT = 0, homeTvL = 0, searchH = 0, searchT = 0, searchL = 0, searchW = 0;
    private LinearLayout searchLl, searchFixedLl;
    private TextView searchBtnTv, searchBtnTvFixed;
    private double searchHStep = 0;
    private double searchLStep = 0;
    private double searchTStep = 0;
    private double searchWStep = 0;
    private double homeTvTStep = 0;
    private double homeTvLStep = 0;

    private int mainTabTop = 0;

    private View topFixedLl, headerTopFl;
    private Banner bannerView;
    private final List<String> bannerUrls = new ArrayList<>();
    private final List<YSwiperBean.ListBean> bannerBeans = new ArrayList<>();
    private View drugListView;
    private MallDrugRecyclerView drugRecyclerView;
    private LinearLayout specialLlView;
    private View qualifyView;
    //    private final Gson gson = new Gson();
    private final Gson gson = new GsonBuilder().
            registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                @Override
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if (src == src.longValue())
                        return new JsonPrimitive(src.longValue());
                    return new JsonPrimitive(src);
                }
            }).create();
    private String doctorId = "";
    private View toTopTv;
    private View bannerCartView;
    private LinearLayout homeNoSearchFixedLl;
    private LinearLayout contentLl;
    private boolean isHasSearch = false;
    private Context context;
    private ViewFlipper viewFlipper, viewFlipperFixed;

    @Override
    public int bondLayout() {
        return R.layout.fragment_mall;
    }

    @Override
    public void initView() {
        context = getContext();
        nestedScrollView = findViewById(R.id.nested_scrollview);
        homeTv = findViewById(R.id.tv_home);
        homeFixedTv = findViewById(R.id.tv_home_fixed);
        searchLl = findViewById(R.id.ll_search);
        searchFixedLl = findViewById(R.id.ll_search_fixed);
        searchBtnTv = findViewById(R.id.tv_search_btn);
        searchBtnTvFixed = findViewById(R.id.tv_search_btn_fixed);
        topFixedLl = findViewById(R.id.ll_top_fixed);
        headerTopFl = findViewById(R.id.fl_header_top);
        bannerView = findViewById(R.id.bannerView);
        drugListView = findViewById(R.id.drug_list_view);
        drugRecyclerView = findViewById(R.id.mall_drug_recycler_view);
        specialLlView = findViewById(R.id.ll_special);
        qualifyView = findViewById(R.id.view_qualify);
        toTopTv = findViewById(R.id.iv_to_top);
        bannerCartView = findViewById(R.id.cart_view_banner);
        contentLl = findViewById(R.id.ll_content);
        homeNoSearchFixedLl = findViewById(R.id.ll_home_no_search_fixed);
        viewFlipper = findViewById(R.id.view_flipper);
        viewFlipperFixed = findViewById(R.id.view_flipper_fixed);
        initNoSearchView();

        refreshViewFlipper(viewFlipper, null);
        refreshViewFlipper(viewFlipperFixed, null);
    }

    private void refreshViewFlipper(ViewFlipper viewFlipper, List<SecretWordBean.SecretWord> secretWords) {
        viewFlipper.removeAllViews();
        if (secretWords == null || ListUtil.getSize(secretWords) <= 0) {
            if (viewFlipper.isFlipping()) {
                viewFlipper.stopFlipping();
            }
            viewFlipper.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    gotoSearch(null, false);
                }
            });
            return;
        }
        viewFlipper.setFlipInterval(3 * 1000);

        viewFlipper.setOutAnimation(
                AnimationUtils.loadAnimation(context, R.anim.filpper_out)
        );
        viewFlipper.setInAnimation(
                AnimationUtils.loadAnimation(context, R.anim.flipper_in)
        );

        for (SecretWordBean.SecretWord secretWord : secretWords) {
            if (secretWord == null || TextUtils.isEmpty(secretWord.getKeyword())) {
                continue;
            }
            TextView view = (TextView) LayoutInflater.from(context).inflate(R.layout.layout_flipper_search, viewFlipper, false);
            view.setText(secretWord.getKeyword());
            view.setTag(R.id.secret_word_id, gson.toJson(secretWord));
            viewFlipper.addView(view);
        }

        if (!viewFlipper.isFlipping()) {
            viewFlipper.startFlipping();
        }
        viewFlipper.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewFlipper == null) {
                    return;
                }
                gotoSearch(viewFlipper, false);

            }
        });
    }

    public void getSecretWord() {
        RequestParams params = new RequestParams();
        params.put("pageIndex", 1);
//        params.put("pageSize", 20);
        HttpUtils.get(AllStringConstants.getSecretWord, params, new HttpCallBack<SecretWordBean>() {
            @Override
            public void onSuccess(SecretWordBean wordBean, int code) {
                if (wordBean != null && wordBean.isResult() && wordBean.getData() != null && ListUtil.getSize(wordBean.getData().getDataList()) > 0) {

                    List<SecretWordBean.SecretWord> secretWords = wordBean.getData().getDataList();
                    refreshViewFlipper(viewFlipper, secretWords);
                    refreshViewFlipper(viewFlipperFixed, secretWords);
                } else {
                    refreshViewFlipper(viewFlipper, null);
                    refreshViewFlipper(viewFlipperFixed, null);
                }
            }

            @Override
            public void onFailure(String s, int i) {
                ALog.e("searchUI", "on failure: " + s + " " + i);
                refreshViewFlipper(viewFlipper, null);
                refreshViewFlipper(viewFlipperFixed, null);
            }
        });
    }

    private void initNoSearchView() {
        if (topFixedLl.getVisibility() != View.INVISIBLE) {
            topFixedLl.setVisibility(View.INVISIBLE);
        }
        if (headerTopFl.getVisibility() != View.INVISIBLE) {
            headerTopFl.setVisibility(View.INVISIBLE);
        }
        if (homeNoSearchFixedLl.getVisibility() != View.VISIBLE) {
            homeNoSearchFixedLl.setVisibility(View.VISIBLE);
        }

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) contentLl.getLayoutParams();
        int topMargin = -ScreenUtils.dip2px(context, 135);
        if (layoutParams.topMargin != topMargin) {
            layoutParams.topMargin = topMargin;
            contentLl.setLayoutParams(layoutParams);
        }
    }

    private void initShowSearchView() {
        if (headerTopFl.getVisibility() != View.VISIBLE) {
            headerTopFl.setVisibility(View.VISIBLE);
        }
        if (topFixedLl.getVisibility() != View.INVISIBLE) {
            topFixedLl.setVisibility(View.INVISIBLE);
        }
        if (homeNoSearchFixedLl.getVisibility() != View.GONE) {
            homeNoSearchFixedLl.setVisibility(View.GONE);
        }

        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) contentLl.getLayoutParams();
        int topMargin = -ScreenUtils.dip2px(context, 75);
        if (layoutParams.topMargin != topMargin) {
            layoutParams.topMargin = topMargin;
            contentLl.setLayoutParams(layoutParams);
        }
    }

    @Override
    public void initData() {
//        bannerUrls.add("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F013d1d563828276ac7259e0f3b05b7.png%401280w_1l_2o_100sh.png&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652843777&t=50d130269e1b004a56360124b3a5563e");
//        bannerUrls.add("https://img1.baidu.com/it/u=1105205742,1332706467&fm=253&fmt=auto&app=138&f=JPEG?w=1920&h=400");
//        bannerUrls.add("https://img0.baidu.com/it/u=3220456217,2909500929&fm=253&fmt=auto&app=138&f=JPEG?w=1600&h=500");
        bannerView.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                try {
                    Glide.with(context).load(path).into(imageView);
                } catch (Throwable throwable) {

                }
            }
        });
//        bannerView.setImages(bannerUrls);
        bannerView.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                ClickUtils.sendEvent(ClickApi.Mall.click_banner, getActivity(), "电商首页banner点击");
                if (ListUtil.getSize(bannerBeans) > position && bannerBeans.get(position) != null) {
                    String load = bannerBeans.get(position).getAppRoute();
                    if (!TextUtils.isEmpty(load) && (load.startsWith("http") || load.startsWith("https"))) {
                        String passportId = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_passportId, "");
                        String token = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.token, null);
                        String url = load.replace("${passportId}", passportId + "");
                        url = url.replace("${token}", token + "");
                        if (url.contains("${timestamp}")) {
                            url = url.replace("${timestamp}", System.currentTimeMillis() + "");
                        }
                        ARouter.getInstance().build(ARouterConstants.MineWebviewActivity)
//                                                            .withString("title", bannerBean.getTitle())
                                .withBoolean("ishtml", false)
                                .withBoolean("isNotReceivedTitle", false)
                                .withString("url", url)
                                .withBoolean("isShowLoading", true).navigation();
                    }
                }
            }
        });
        bannerView.isAutoPlay(true);
        bannerView.setDelayTime(1500);

        ClickUtils.setFastOnClickListener(searchBtnTvFixed, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoSearch(viewFlipperFixed, true);
            }
        });
        ClickUtils.setFastOnClickListener(searchBtnTv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoSearch(viewFlipper, true);
            }
        });

        ClickUtils.setFastOnClickListener(toTopTv, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nestedScrollView.scrollTo(0, 0);
                drugRecyclerView.scrollToPosition(0);
                if (topFixedLl.getVisibility() != View.INVISIBLE) {
                    topFixedLl.setVisibility(View.INVISIBLE);
                }
                nestedScrollView.setNeedScroll(true);
                drugRecyclerView.setDrugsTlFixed(false);
                if (toTopTv.getVisibility() != View.GONE) {
                    toTopTv.setVisibility(View.GONE);
                }
            }
        });

//        bannerView.start();

//        getMallHomeData();
    }

    public void gotoSearch(ViewFlipper viewFlipper, boolean isSearch) {
        if (TextUtils.isEmpty(doctorId)) {
            return;
        }
        ClickUtils.sendEvent(ClickApi.Mall.click_search, getActivity(), "电商首页搜索框点击");
        String keyWord = "";
        String searchId = "";
        if (viewFlipper != null && viewFlipper.getCurrentView() != null && viewFlipper.getCurrentView().getTag(R.id.secret_word_id) != null) {
            try {
                SecretWordBean.SecretWord secretWord = gson.fromJson((String) viewFlipper.getCurrentView().getTag(R.id.secret_word_id), SecretWordBean.SecretWord.class);
                keyWord = secretWord.getKeyword();
                searchId = secretWord.getId();
            } catch (Throwable throwable) {
                ALog.e("searchUI", "throwable:" + throwable.getMessage());
            }
        }
        ALog.e("searchUI", keyWord + " ==> " + searchId);
        Bundle bundle = new Bundle();
        if (!TextUtils.isEmpty(keyWord)) {
            bundle.putString("searchKey", keyWord);
        }
        if (!TextUtils.isEmpty(searchId)) {
            bundle.putString("searchId", searchId);
        }
        bundle.putBoolean("isSearch", isSearch);
        bundle.putString("doctorId", doctorId);
        DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
        AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
        if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
            bundle.putString("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
//                    paramsJSON.put("lat", whCityBean.getLat());
//                    paramsJSON.put("lng", whCityBean.getLng());
        } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
            bundle.putString("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
//                    paramsJSON.put("lat", aMapLocation.getLatitude());
//                    paramsJSON.put("lng", aMapLocation.getLongitude());
        }
        MallUtils.push(getContext(), KitArouterConstants.CART_DOCTORBUNDLE, KitArouterConstants.Cart.Retailers, bundle);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
//            noticeView.pause();
        } else {
//            initData();
//            noticeView.start();
            getMallHomeData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        getMallHomeData();
        ClickUtils.sendEvent(ClickApi.Mall.page_show, getActivity(), "电商首页载入");

    }

    private void getMallHomeData() {
        LoadingUtils.getLoadingUtils(getContext()).showLoading();
        HttpUtils.post(AllStringConstants.MallUrl.GetMallHomePage, new HttpCallBack<MallHomeBean>() {
            @Override
            public void onSuccess(MallHomeBean mallHomeBean, int i) {
                if (i == 200 && mallHomeBean != null && mallHomeBean.isResult() && mallHomeBean.getData() != null) {
                    MallHomeContentBean contentBean = gson.fromJson(mallHomeBean.getData().getContent(), MallHomeContentBean.class);
                    specialLlView.removeAllViews();
                    bannerCartView.setVisibility(View.GONE);
                    drugRecyclerView.setVisibility(View.GONE);
                    qualifyView.setVisibility(View.GONE);
                    nestedScrollView.scrollTo(0, 0);
                    isHasSearch = false;
                    onNestedScroll(nestedScrollView.getScrollY());
                    initNoSearchView();
                    for (MallHomeContentBean.Data data : contentBean.getData()) {
                        try {
                            String valueStr = gson.toJson(data.getValue());
                            doctorId = mallHomeBean.getData().getDoctorId();
                            switch (data.getName()) {
                                case YSearch: {
                                    initShowSearchView();
                                    isHasSearch = true;
                                    getSecretWord();
                                    break;
                                }
                                case YImage: {
                                    YImageBean imageBean = gson.fromJson(valueStr, YImageBean.class);
                                    if (imageBean != null) {
                                        String load = imageBean.getRoute();
                                        qualifyView.setVisibility(View.VISIBLE);
                                        ClickUtils.setFastOnClickListener(qualifyView, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                //TODO 埋点
                                                ClickUtils.sendEvent(ClickApi.Mall.click_qualify, getActivity(), "商城首页医疗资格点击");
                                                if (getContext() == null) {
                                                    return;
                                                }
                                                if (!TextUtils.isEmpty(load) && (load.startsWith("http") || load.startsWith("https"))) {
                                                    String passportId = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.account_passportId, "");
                                                    String token = SharedPreferencesUtils.getInstance().getString(UserInfoConstants.token, null);
                                                    String url = load.replace("${passportId}", passportId + "");
                                                    url = url.replace("${token}", token + "");
                                                    if (url.contains("${timestamp}")) {
                                                        url = url.replace("${timestamp}", System.currentTimeMillis() + "");
                                                    }
                                                    ARouter.getInstance().build(ARouterConstants.MineWebviewActivity)
//                                                            .withString("title", bannerBean.getTitle())
                                                            .withBoolean("ishtml", false)
                                                            .withBoolean("isNotReceivedTitle", false)
                                                            .withString("url", url)
                                                            .withBoolean("isShowLoading", true).navigation();
                                                }
                                            }

                                        });
                                    }

                                    break;
                                }
                                case YSwiper: {
                                    YSwiperBean swiperBean = gson.fromJson(valueStr, YSwiperBean.class);
                                    if (swiperBean != null && ListUtil.getSize(swiperBean.getList()) > 0) {
                                        bannerCartView.setVisibility(View.VISIBLE);
                                        bannerUrls.clear();
                                        bannerBeans.clear();
                                        bannerBeans.addAll(swiperBean.getList());
                                        for (YSwiperBean.ListBean listBean : swiperBean.getList()) {
                                            bannerUrls.add(listBean.getImgUrl());
                                        }
                                        bannerView.setImages(bannerUrls);
                                        bannerView.start();
                                    }
                                    break;
                                }
                                case YCategoryList: {
                                    YCategoryListBean categoryList = gson.fromJson(valueStr, YCategoryListBean.class);
                                    if (categoryList != null) {
                                        MallClassifyView mallClassifyView = new MallClassifyView(getContext());
                                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                        layoutParams.topMargin = ScreenUtils.dip2px(getContext(), 10);
                                        mallClassifyView.setLayoutParams(layoutParams);
                                        mallClassifyView.setCategoryListBean(categoryList, doctorId);
                                        specialLlView.addView(mallClassifyView);
                                    }
                                    break;
                                }
                                case YHotSale: {
                                    YHotSaleBean saleBean = gson.fromJson(valueStr, YHotSaleBean.class);
                                    if (saleBean != null) {
                                        MallHotView mallHotView = new MallHotView(getContext());
                                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                        layoutParams.topMargin = ScreenUtils.dip2px(getContext(), 10);
                                        mallHotView.setLayoutParams(layoutParams);
                                        mallHotView.setBean(saleBean, doctorId);
                                        specialLlView.addView(mallHotView);
                                    }
                                    break;
                                }
                                case YSpecial: {
                                    YSpecialBean specialBean = gson.fromJson(valueStr, YSpecialBean.class);
                                    if (specialBean != null) {
                                        MallCardView mallCardView = new MallCardView(getContext());
                                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                        layoutParams.topMargin = ScreenUtils.dip2px(getContext(), 10);
                                        mallCardView.setLayoutParams(layoutParams);
                                        mallCardView.setSpecialBean(specialBean, doctorId);
                                        specialLlView.addView(mallCardView);
                                    }
                                    break;
                                }
                                case YWaterfallFlow: {
                                    YWaterfallFlowBean waterfallFlow = gson.fromJson(valueStr, YWaterfallFlowBean.class);
                                    if (waterfallFlow != null) {
                                        drugRecyclerView.setVisibility(View.VISIBLE);
                                        drugRecyclerView.setData(waterfallFlow.getId(), doctorId);
                                    }
                                    break;
                                }
                            }
                        } catch (Throwable throwable) {
                        }
                    }
                } else if (mallHomeBean != null && !TextUtils.isEmpty(mallHomeBean.getMsg())) {
                    ToastUtils.showShort(mallHomeBean.getMsg());
                }

//                nestedScrollView.setNeedScroll(true);
//                drugRecyclerView.setDrugsTlFixed(false);
//                if (toTopTv.getVisibility() != View.GONE) {
//                    toTopTv.setVisibility(View.GONE);
//                }
                onNestedScroll(nestedScrollView.getScrollY());
                LoadingUtils.getLoadingUtils(getContext()).dismissLoading();
            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(getContext()).dismissLoading();
            }
        });
    }

    @Override
    public void initEvent() {
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                onNestedScroll(scrollY);
            }
        });
    }

    private void onNestedScroll(int scrollY) {
        refreshScrollData();
        if (!isHasSearch) {
            initNoSearchView();
//            return;
        } else {
            initShowSearchView();
        }
        if (scrollY > changeScrollH) {
            //头部搜索框固定
            if (topFixedLl.getVisibility() != View.VISIBLE && isHasSearch) {
                topFixedLl.setVisibility(View.VISIBLE);
            }
            if (headerTopFl.getVisibility() != View.INVISIBLE) {
                headerTopFl.setVisibility(View.INVISIBLE);
            }

            if (scrollY > (drugListView.getTop() + contentLl.getTop() - topFixedLl.getTop() - topFixedLl.getMeasuredHeight())) {
                nestedScrollView.setNeedScroll(false);
                drugRecyclerView.setDrugsTlFixed(true);
//                        if (toTopTv.getVisibility() != View.VISIBLE) {
//                            toTopTv.setVisibility(View.VISIBLE);
//                        }
            } else {
                drugRecyclerView.scrollToPosition(0);
                nestedScrollView.setNeedScroll(true);
                drugRecyclerView.setDrugsTlFixed(false);
//                if (toTopTv.getVisibility() != View.GONE) {
//                    toTopTv.setVisibility(View.GONE);
//                }
            }

        } else if (scrollY > 0) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) homeTv.getLayoutParams();
            layoutParams.leftMargin = (int) (homeTvL + homeTvLStep * scrollY);
            layoutParams.topMargin = (int) (homeTvT + homeTvTStep * scrollY + scrollY);
            homeTv.setLayoutParams(layoutParams);
//
            FrameLayout.LayoutParams currentSearchLp = (FrameLayout.LayoutParams) searchLl.getLayoutParams();
            currentSearchLp.height = (int) (searchH + searchHStep * scrollY);
            currentSearchLp.width = (int) (searchW + searchWStep * scrollY);
            currentSearchLp.topMargin = (int) (searchT + scrollY + searchTStep * scrollY);
            currentSearchLp.leftMargin = (int) (searchL + searchLStep * scrollY);
            searchLl.setLayoutParams(currentSearchLp);

            if (topFixedLl.getVisibility() != View.INVISIBLE) {
                topFixedLl.setVisibility(View.INVISIBLE);
            }
            if (headerTopFl.getVisibility() != View.VISIBLE && isHasSearch) {
                headerTopFl.setVisibility(View.VISIBLE);
            }

            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) headerTopFl.getLayoutParams();
            params.topMargin = -scrollY;
            headerTopFl.setLayoutParams(params);

            nestedScrollView.setNeedScroll(true);
            drugRecyclerView.setDrugsTlFixed(false);
//            if (toTopTv.getVisibility() != View.GONE) {
//                toTopTv.setVisibility(View.GONE);
//            }
        } else {
            FrameLayout.LayoutParams layoutParam = (FrameLayout.LayoutParams) homeTv.getLayoutParams();
            layoutParam.leftMargin = homeTvL;
            layoutParam.topMargin = homeTvT;
            homeTv.setLayoutParams(layoutParam);

            FrameLayout.LayoutParams layoutParam1 = (FrameLayout.LayoutParams) searchLl.getLayoutParams();
            layoutParam1.height = searchH;
            layoutParam1.width = searchW;
            layoutParam1.topMargin = searchT;
            layoutParam1.leftMargin = searchL;
            searchLl.setLayoutParams(layoutParam1);
            if (topFixedLl.getVisibility() != View.INVISIBLE) {
                topFixedLl.setVisibility(View.INVISIBLE);
            }
            if (headerTopFl.getVisibility() != View.VISIBLE && isHasSearch) {
                headerTopFl.setVisibility(View.VISIBLE);
            }
            FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) headerTopFl.getLayoutParams();
            params.topMargin = 0;
            headerTopFl.setLayoutParams(params);

            nestedScrollView.setNeedScroll(true);
            drugRecyclerView.setDrugsTlFixed(false);
//            if (toTopTv.getVisibility() != View.GONE) {
//                toTopTv.setVisibility(View.GONE);
//            }
        }
    }

    private void refreshScrollData() {

        View view = MallUtils.getMainTabLayoutView(getActivity());
        if (view != null) {
            mainTabTop = view.getTop();
        }
        if (mainTabTop > 0) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) drugListView.getLayoutParams();
            layoutParams.height = mainTabTop - topFixedLl.getHeight() - topFixedLl.getTop() + 1;
            drugListView.setLayoutParams(layoutParams);
        }


        if (homeTvT <= 0) {
            homeTvT = ((FrameLayout.LayoutParams) homeTv.getLayoutParams()).topMargin;
            homeTvL = ((FrameLayout.LayoutParams) homeTv.getLayoutParams()).leftMargin;
            searchH = searchLl.getMeasuredHeight();
            searchT = ((FrameLayout.LayoutParams) searchLl.getLayoutParams()).topMargin;
            searchL = searchLl.getLeft();
            searchW = searchLl.getMeasuredWidth();

            homeTvLStep = 1.0 * (homeFixedTv.getLeft() - homeTv.getLeft()) / changeScrollH;
            homeTvTStep = 1.0 * (homeFixedTv.getTop() - homeTv.getTop()) / changeScrollH;
            searchHStep = 1.0 * (searchFixedLl.getMeasuredHeight() - searchH) / changeScrollH;
            searchTStep = 1.0 * (searchFixedLl.getTop() - searchLl.getTop()) / changeScrollH;
            searchWStep = 1.0 * (searchFixedLl.getMeasuredWidth() - searchW) / changeScrollH;
            searchLStep = 1.0 * (searchFixedLl.getLeft() - searchL) / changeScrollH;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        MallObserver.getInstance().addObserver(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        MallObserver.getInstance().deleteObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        if (arg != null && arg instanceof MallObserver.MallObserverBean) {
            switch (((MallObserver.MallObserverBean) arg).getType()) {
                case TYPE_DRUGS_LOAD_ONE_PAGE: {
                    onNestedScroll(nestedScrollView.getScrollY());
                    break;
                }
            }
        }
    }
}
